<template>
  <div class="workorder-detail-container">
    <div class="header-section">
      <div class="title-section">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/workorder' }">工单列表</el-breadcrumb-item>
          <el-breadcrumb-item>工单详情</el-breadcrumb-item>
        </el-breadcrumb>
        <h1 class="page-title">{{ workOrder.title || '工单详情' }}</h1>
      </div>
      <div class="action-buttons">
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" @click="handleEdit" v-if="canEdit">编辑</el-button>
      </div>
    </div>

    <div class="content-section" v-loading="loading">
      <!-- 工单基本信息 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>工单信息</span>
            <el-tag :type="getStatusType(workOrder.statusId)" effect="light">{{ workOrder.statusName }}</el-tag>
          </div>
        </template>
        
        <div class="info-grid">
          <div class="info-item">
            <span class="label">工单编号</span>
            <span class="value">{{ workOrder.orderNo }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间</span>
            <span class="value">{{ formatDate(workOrder.createTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">工单类型</span>
            <span class="value">
              <el-tag type="success" size="small" effect="light">
                {{ workOrder.typeName || '未知类型' }}
              </el-tag>
            </span>
          </div>
          <div class="info-item">
            <span class="label">优先级</span>
            <span class="value">
              <el-tag :type="getPriorityType(workOrder.priority)" size="small" effect="light">
                {{ getPriorityText(workOrder.priority) || '未知' }}
              </el-tag>
            </span>
          </div>
          <div class="info-item">
            <span class="label">创建人</span>
            <span class="value">{{ workOrder.creatorName }}</span>
          </div>
          <div class="info-item">
            <span class="label">处理人</span>
            <span class="value">{{ workOrder.handlerName || '未分配' }}</span>
          </div>
          <div class="info-item">
            <span class="label">期望完成时间</span>
            <span class="value">{{ formatDate(workOrder.expectedFinishTime) || '无' }}</span>
          </div>
          <div class="info-item">
            <span class="label">实际完成时间</span>
            <span class="value">{{ formatDate(workOrder.actualFinishTime) || '未完成' }}</span>
          </div>
        </div>

        <div class="content-box">
          <div class="content-header">工单内容</div>
          <div class="content-body">{{ workOrder.content }}</div>
        </div>
        
        <!-- 评价信息 -->
        <div class="evaluation-section" v-if="workOrder.evaluationScore">
          <div class="content-header">客户评价</div>
          <div class="evaluation-content">
            <div class="evaluation-score">
              <el-rate
                v-model="workOrder.evaluationScore"
                disabled
                show-score
                text-color="#ff9900"
              />
            </div>
            <div class="evaluation-text">{{ workOrder.evaluationContent }}</div>
          </div>
        </div>
      </el-card>
      
      <!-- 处理记录 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>处理记录</span>
            <el-button type="primary" plain size="small" @click="handleAddRecord" v-if="canAddRecord">
              添加处理记录
            </el-button>
          </div>
        </template>
        
        <el-timeline v-if="records.length > 0">
          <el-timeline-item
            v-for="record in records"
            :key="record.id"
            :timestamp="formatDate(record.createTime)"
            :type="getTimelineItemType(record.operationType)"
          >
            <el-card class="timeline-card">
              <template #header>
                <div class="timeline-header">
                  <span>{{ record.operatorName }} - {{ getOperationTypeText(record.operationType) }}</span>
                  <span v-if="record.isInternal" class="internal-tag">内部记录</span>
                </div>
              </template>
              
              <div class="timeline-content">
                <p v-if="record.fromStatusId !== record.toStatusId" class="status-change">
                  状态变更：
                  <el-tag size="small" effect="plain">{{ getStatusName(record.fromStatusId) }}</el-tag>
                  <el-icon class="status-arrow"><ArrowRight /></el-icon>
                  <el-tag size="small" effect="plain">{{ getStatusName(record.toStatusId) }}</el-tag>
                </p>
                <div class="record-content">{{ record.operationContent }}</div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        
        <div class="empty-records" v-else>
          <el-empty description="暂无处理记录" />
        </div>
      </el-card>
      
      <!-- 附件列表 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>附件列表</span>
            <el-button type="primary" plain size="small" @click="handleUpload" v-if="canAddAttachment">
              上传附件
            </el-button>
          </div>
        </template>
        
        <el-table v-if="attachments.length > 0" :data="attachments" style="width: 100%">
          <el-table-column prop="fileName" label="文件名" min-width="180" show-overflow-tooltip />
          <el-table-column prop="fileType" label="类型" width="100" />
          <el-table-column prop="fileSize" label="大小" width="100">
            <template #default="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="uploaderName" label="上传人" width="120" />
          <el-table-column prop="createTime" label="上传时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleDownload(scope.row)">下载</el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDeleteAttachment(scope.row)"
                v-if="canDeleteAttachment"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="empty-attachments" v-else>
          <el-empty description="暂无附件" />
        </div>
      </el-card>
    </div>
    
    <!-- 添加处理记录对话框 -->
    <el-dialog
      v-model="recordDialogVisible"
      title="添加处理记录"
      width="600px"
      destroy-on-close
    >
      <el-form :model="recordForm" label-width="100px" :rules="recordRules" ref="recordFormRef">
        <el-form-item label="操作类型" prop="operationType">
          <el-select v-model="recordForm.operationType" placeholder="请选择操作类型">
            <el-option label="处理中" value="PROCESSING" />
            <el-option label="转交" value="TRANSFER" />
            <el-option label="完成" value="COMPLETE" />
            <el-option label="关闭" value="CLOSE" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态更新" prop="toStatusId">
          <el-select v-model="recordForm.toStatusId" placeholder="请选择更新后状态">
            <el-option 
              v-for="status in statusOptions" 
              :key="status.id" 
              :label="status.name" 
              :value="status.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="处理内容" prop="operationContent">
          <el-input
            v-model="recordForm.operationContent"
            type="textarea"
            rows="4"
            placeholder="请输入处理内容"
          />
        </el-form-item>
        
        <el-form-item label="内部记录">
          <el-switch v-model="recordForm.isInternal" />
          <span class="tips">内部记录仅工作人员可见</span>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="recordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRecord">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 上传附件对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传附件"
      width="500px"
      destroy-on-close
    >
      <el-upload
        class="upload-demo"
        action=""
        :http-request="uploadFile"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        multiple
        :limit="5"
        :on-exceed="handleExceed"
      >
        <el-button type="primary">点击上传</el-button>
        <template #tip>
          <div class="el-upload__tip">
            文件大小不超过10MB
          </div>
        </template>
      </el-upload>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadDialogVisible = false">完成</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import { workOrder as workOrderApi } from '@/api'
import { useStore } from 'vuex'

export default {
  name: 'WorkOrderDetail',
  components: { ArrowRight },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const loading = ref(false)
    const recordFormRef = ref(null)
    
    // 工单详情数据
    const workOrder = ref({})
    const records = ref([])
    const attachments = ref([])
    const statusOptions = ref([])
    const typeOptions = ref([])
    
    // 权限控制
    const canEdit = computed(() => {
      // TODO: 根据工单状态和用户角色判断是否可编辑
      return true
    })
    
    const canAddRecord = computed(() => {
      // TODO: 根据工单状态和用户角色判断是否可添加记录
      return true
    })
    
    const canAddAttachment = computed(() => {
      // TODO: 根据工单状态和用户角色判断是否可添加附件
      return true
    })
    
    const canDeleteAttachment = computed(() => {
      // TODO: 根据工单状态和用户角色判断是否可删除附件
      return true
    })
    
    // 对话框控制
    const recordDialogVisible = ref(false)
    const uploadDialogVisible = ref(false)
    
    // 处理记录表单
    const recordForm = reactive({
      orderId: null,
      operationType: '',
      fromStatusId: null,
      toStatusId: null,
      operationContent: '',
      isInternal: false
    })
    
    const recordRules = {
      operationType: [{ required: true, message: '请选择操作类型', trigger: 'change' }],
      toStatusId: [{ required: true, message: '请选择更新后状态', trigger: 'change' }],
      operationContent: [{ required: true, message: '请输入处理内容', trigger: 'blur' }]
    }
    
    // 获取工单详情
    const getWorkOrderDetail = async () => {
      const id = route.params.id
      if (!id) return
      
      loading.value = true
      try {
        const res = await workOrderApi.getWorkOrderDetail(id)
        if (res.data && res.data.code === 200) {
          workOrder.value = res.data.data || {}
          
          // 设置处理记录的初始状态
          if (workOrder.value.statusId) {
            recordForm.fromStatusId = workOrder.value.statusId
            recordForm.toStatusId = workOrder.value.statusId
          }
          recordForm.orderId = workOrder.value.id
          
          // 获取处理记录和附件列表
          getWorkOrderRecords(id)
          getWorkOrderAttachments(id)
          
          // 确保已获取类型选项
          await getTypeOptions()
          
          // 处理工单类型名称
          if (workOrder.value.typeId && !workOrder.value.typeName) {
            const type = typeOptions.value.find(t => t.id === workOrder.value.typeId)
            if (type) {
              workOrder.value.typeName = type.name
            }
          }
        } else {
          ElMessage.error(res.data?.message || '获取工单详情失败')
        }
      } catch (error) {
        console.error('获取工单详情失败', error)
        ElMessage.error('获取工单详情失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取工单状态选项
    const getStatusOptions = async () => {
      try {
        const res = await workOrderApi.getWorkOrderStatuses()
        if (res.data && res.data.code === 200) {
          statusOptions.value = res.data.data || []
        }
      } catch (error) {
        console.error('获取工单状态列表失败', error)
      }
    }
    
    // 获取状态名称
    const getStatusName = (statusId) => {
      if (!statusId) return ''
      const status = statusOptions.value.find(s => s.id === statusId)
      return status ? status.name : ''
    }
    
    // 获取工单处理记录
    const getWorkOrderRecords = async (orderId) => {
      try {
        const res = await workOrderApi.getWorkOrderRecords(orderId)
        if (res.data && res.data.code === 200) {
          records.value = res.data.data || []
        } else {
          console.error('获取处理记录失败', res.data?.message)
        }
      } catch (error) {
        console.error('获取处理记录失败', error)
      }
    }
    
    // 获取工单附件
    const getWorkOrderAttachments = async (orderId) => {
      try {
        const res = await workOrderApi.getWorkOrderAttachments(orderId)
        if (res.data && res.data.code === 200) {
          attachments.value = res.data.data || []
        } else {
          console.error('获取附件列表失败', res.data?.message)
        }
      } catch (error) {
        console.error('获取附件列表失败', error)
      }
    }
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleString()
    }
    
    // 格式化文件大小
    const formatFileSize = (size) => {
      if (!size) return '0 B'
      
      const units = ['B', 'KB', 'MB', 'GB', 'TB']
      let i = 0
      while (size >= 1024 && i < units.length - 1) {
        size /= 1024
        i++
      }
      
      return `${size.toFixed(2)} ${units[i]}`
    }
    
    // 获取状态类型（用于显示不同颜色）
    const getStatusType = (statusId) => {
      // 根据状态ID返回不同类型
      const statusMap = {
        1: 'info',    // 待处理
        2: 'warning', // 处理中
        3: '',        // 待反馈
        4: 'warning', // 待验收
        5: 'success', // 已完成
        6: 'info',    // 已关闭
        7: 'danger'   // 已取消
      }
      return statusMap[statusId] || ''
    }
    
    // 获取优先级类型（用于显示不同颜色）
    const getPriorityType = (priority) => {
      const priorityMap = {
        1: 'info',    // 低
        2: '',        // 中
        3: 'warning', // 高
        4: 'danger'   // 紧急
      }
      return priorityMap[priority] || ''
    }
    
    // 获取优先级文本
    const getPriorityText = (priority) => {
      const textMap = {
        1: '低',
        2: '中',
        3: '高',
        4: '紧急'
      }
      return textMap[priority] || '未知'
    }
    
    // 获取时间线项目类型
    const getTimelineItemType = (operationType) => {
      const typeMap = {
        'PROCESSING': 'warning',
        'TRANSFER': 'info',
        'COMPLETE': 'success',
        'CLOSE': 'info',
        'CANCEL': 'danger'
      }
      return typeMap[operationType] || 'primary'
    }
    
    // 获取操作类型文本
    const getOperationTypeText = (operationType) => {
      const textMap = {
        'PROCESSING': '处理中',
        'TRANSFER': '转交',
        'COMPLETE': '完成',
        'CLOSE': '关闭',
        'CANCEL': '取消'
      }
      return textMap[operationType] || operationType
    }
    
    // 返回列表页
    const goBack = () => {
      router.push('/workorder')
    }
    
    // 编辑工单
    const handleEdit = () => {
      router.push(`/workorder/edit/${workOrder.value.id}`)
    }
    
    // 添加处理记录
    const handleAddRecord = () => {
      recordDialogVisible.value = true
    }
    
    // 提交处理记录
    const submitRecord = async () => {
      if (!recordFormRef.value) return
      
      await recordFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const res = await workOrderApi.addWorkOrderRecord(recordForm)
            if (res.data && res.data.code === 200) {
              recordDialogVisible.value = false
              ElMessage.success('添加处理记录成功')
              
              // 如果状态发生变化，更新工单状态
              if (recordForm.fromStatusId !== recordForm.toStatusId) {
                await workOrderApi.updateWorkOrderStatus({
                  id: workOrder.value.id,
                  statusId: recordForm.toStatusId,
                  content: recordForm.operationContent
                })
              }
              
              // 刷新工单详情
              getWorkOrderDetail()
            } else {
              ElMessage.error(res.data?.message || '添加处理记录失败')
            }
          } catch (error) {
            console.error('添加处理记录失败', error)
            ElMessage.error('添加处理记录失败')
          }
        }
      })
    }
    
    // 上传附件
    const handleUpload = () => {
      uploadDialogVisible.value = true
    }
    
    // 自定义上传方法
    const uploadFile = async (options) => {
      try {
        const formData = new FormData()
        formData.append('file', options.file)
        formData.append('orderId', workOrder.value.id)
        
        const res = await workOrderApi.uploadWorkOrderAttachment(formData)
        
        if (res.data && res.data.code === 200) {
          options.onSuccess(res.data.data)
          // 刷新附件列表
          getWorkOrderAttachments(workOrder.value.id)
          ElMessage.success('上传成功')
        } else {
          options.onError(new Error(res.data?.message || '上传失败'))
          ElMessage.error(res.data?.message || '上传失败')
        }
      } catch (error) {
        console.error('上传附件失败', error)
        options.onError(new Error('上传失败'))
        ElMessage.error('上传失败')
      }
    }
    
    // 上传相关方法
    const handlePreview = (file) => {
      console.log('预览文件', file)
    }
    
    const handleRemove = (file, fileList) => {
      console.log('移除文件', file, fileList)
    }
    
    const handleExceed = (files, fileList) => {
      ElMessage.warning(`最多同时上传5个文件，当前已选择${fileList.length}个文件`)
    }
    
    const beforeRemove = (file) => {
      return ElMessageBox.confirm(`确定移除 ${file.name}？`)
    }
    
    // 下载附件
    const handleDownload = (file) => {
      try {
        const downloadUrl = workOrderApi.getAttachmentDownloadUrl(file.id)
        // 使用窗口打开下载链接
        window.open(downloadUrl)
      } catch (error) {
        console.error('下载附件失败', error)
        ElMessage.error('下载附件失败')
      }
    }
    
    // 删除附件
    const handleDeleteAttachment = (file) => {
      ElMessageBox.confirm(
        `确定要删除附件 ${file.fileName} 吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const res = await workOrderApi.deleteWorkOrderAttachment(file.id)
          if (res.data && res.data.code === 200) {
            ElMessage.success('删除附件成功')
            // 刷新附件列表
            getWorkOrderAttachments(workOrder.value.id)
          } else {
            ElMessage.error(res.data?.message || '删除附件失败')
          }
        } catch (error) {
          console.error('删除附件失败', error)
          ElMessage.error('删除附件失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 获取工单类型选项
    const getTypeOptions = async () => {
      try {
        console.log('正在获取工单类型列表...')
        const res = await workOrderApi.getWorkOrderTypes()
        if (res.data && res.data.code === 200) {
          typeOptions.value = res.data.data || []
          console.log('成功获取工单类型，数量:', typeOptions.value.length)
        } else {
          console.error('获取工单类型失败:', res.data?.message)
        }
      } catch (error) {
        console.error('获取工单类型列表失败', error)
      }
    }

    onMounted(() => {
      getWorkOrderDetail()
      getStatusOptions()
      getTypeOptions()
    })
    
    return {
      loading,
      recordFormRef,
      workOrder,
      records,
      attachments,
      statusOptions,
      typeOptions,
      canEdit,
      canAddRecord,
      canAddAttachment,
      canDeleteAttachment,
      recordDialogVisible,
      uploadDialogVisible,
      recordForm,
      recordRules,
      formatDate,
      formatFileSize,
      getStatusType,
      getPriorityType,
      getPriorityText,  // 添加这个函数到返回对象中
      getTimelineItemType,
      getOperationTypeText,
      getStatusName,
      goBack,
      handleEdit,
      handleAddRecord,
      submitRecord,
      handleUpload,
      uploadFile,
      handlePreview,
      handleRemove,
      handleExceed,
      beforeRemove,
      handleDownload,
      handleDeleteAttachment
    }
  }
}
</script>

<style scoped>
.workorder-detail-container {
  padding: 24px;
  background-color: #f9fafb;
  min-height: calc(100vh - 60px);
}

/* 标题区域 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.title-section {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 32px;
  font-weight: 300;
  color: #262626;
  margin: 8px 0 0;
  letter-spacing: -0.5px;
}

/* 内容区域 */
.content-section {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.detail-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 400;
  color: #303133;
}

/* 信息网格 */
.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.value {
  font-size: 16px;
  color: #303133;
}

/* 内容区域 */
.content-box {
  margin-bottom: 24px;
}

.content-header {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 12px;
  border-left: 3px solid #409EFF;
  padding-left: 10px;
}

.content-body {
  padding: 16px;
  background-color: #f9fafb;
  border-radius: 8px;
  min-height: 100px;
  white-space: pre-wrap;
}

/* 评价区域 */
.evaluation-section {
  margin-top: 16px;
}

.evaluation-content {
  padding: 16px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.evaluation-text {
  margin-top: 12px;
  color: #303133;
}

/* 时间线 */
.timeline-card {
  --el-card-padding: 12px;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.internal-tag {
  font-size: 12px;
  color: #909399;
  background-color: #f4f4f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.status-change {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  color: #909399;
}

.status-arrow {
  font-size: 16px;
  color: #909399;
}

.record-content {
  white-space: pre-wrap;
}

/* 空状态 */
.empty-records, 
.empty-attachments {
  padding: 40px 0;
}

/* 上传附件 */
.upload-demo {
  width: 100%;
}

.tips {
  font-size: 12px;
  color: #909399;
  margin-left: 12px;
}
</style> 
 







